﻿(function ($)
{
    $.modes = {};

    $.modes.active = [];

    $.modes.template = {};

    $.fn.modes = function ()
    {
        var t = $(this);

        $(".scrollable").hiddenScroll();


        $.post('modes-template.html', null, function (data)
        {
            $.modes.template = data;

            $.modes.loadModes(t);

        }, 'html');
    }

    $.modes.loadModes = function (target)
    {
        $.post('bus/load_modes.php', null, function (data)
        {
            for (var i in data.Modes)
            {
                if (data.Modes[i].Selected)
                    $.modes.active.push(data.Modes[i].Name);

                $.modes.newMode(data.Modes[i], target);
            }

            if (typeof ($.modes.onChange) == 'function')
                $.modes.onChange();

        });
    }



    $.modes.newMode = function (mode, target)
    {
        $clone = $($.modes.template).clone();

        $clone.attr('modeId', mode.Id);

        $('.modes-text', $clone).text(mode.Name);

        $clone.click($.modes.item_onClick);

        if (mode.Selected)
        {
            $.modes.select($clone, true)
            $('input', $clone).attr('checked', true);
        }

        target.append($clone);
    }

    $.modes.select = function (mode, value)
    {
        if (value)
        {
            //$('.modes-checkbox', mode).addClass('ui-state-active').css('border-radius', '6px');
            mode.addClass('selected');
            //$('.modes-checkbox', mode).removeClass('ui-state-hover');
        }
        else
        {
            mode.removeClass('selected');

            //$('.modes-checkbox', mode).addClass('ui-state-hover');
            
            //$('.modes-checkbox', mode).removeClass('ui-state-active');
        }
    }

    $.modes.item_onClick = function (event, ui)
    {
        var t = $(this);

        var res = !$(t).hasClass('selected');

        $('input', t).attr('checked', res);

        $.modes.select(t, res);

        $.post('bus/load_elements.php', 'mode=' + t.attr('modeId'), function (data)
        {
            if (res)
            {
                $.modes.active.push($('.modes-text', t).text());

                $.elements.loadElements(t.attr('modeId'))
            }
            else
            {
                $.modes.active = jQuery.grep($.modes.active, function (value)
                {
                    return value != $('.modes-text', t).text();
                });
                $.elements.removeElements(t.attr('modeId'))
            }

            if (typeof ($.modes.onChange) == 'function')
                $.modes.onChange();

        });

    }

})(jQuery);
